# config.py - 配置文件 (使用你的API密钥)
import os
from datetime import timedelta

# ======================
# 🔥 讯飞API配置 (你的密钥)
# ======================
# 星火参数
SPARK_APPID = "0fa3d916"
SPARK_APIKey = "6c8ceef9f3445b36c2819fefe4f3ce73"
SPARK_APISecret = "MDQyOGEzNTcyNjYyOWQxMTE3MWQxZThj"
SPARK_URL = "wss://spark-api.xf-yun.com/v1/x1"
SPARK_DOMAIN = "x1"

# 实时语音识别（RT-ASR）
RTASR_APPID = "0fa3d916"
RTASR_APIKey = "f6fc31b0b971704dae936990b18c6711"

# OCR 与人脸比对私有服务 URL
OCR_URL = "https://api.xf-yun.com/v1/private/sf8e6aca1"
FACE_COMPARE_URL = "https://api.xf-yun.com/v1/private/s67c9c78c"

# 输入文件
RESUME_IMG = "3.jpg"
REGISTERED_IMG = "registered_face.jpg"
CAPTURED_IMG = "captured_face.jpg"

# 语音合成输出路径
OUTPUT_PCM_PATH = "demo.pcm"
OUTPUT_WAV_PATH = "demo.wav"

# ======================
# 🔥 面试系统配置
# ======================

# 面试轮次配置
DEFAULT_INTERVIEW_ROUNDS = 3
QUESTION_TIME_LIMIT = 120  # 每题时间限制（秒）
SPEAKING_TIME = 15  # AI说话时间（秒）

# 身份验证配置
FACE_SIMILARITY_THRESHOLD = 0.6  # 人脸相似度阈值
IDENTITY_VERIFICATION_REQUIRED = True

# 情绪分析配置 (Face++)
EMOTION_SAMPLE_RATE = 2  # 情绪采样频率（秒）
ENABLE_EMOTION_ANALYSIS = True

# 音频配置
AUDIO_SAMPLE_RATE = 16000
AUDIO_CHUNK_SIZE = 640
AUDIO_FORMAT = 'wav'

# ======================
# 🔥 文件存储配置
# ======================
# 文件上传配置
UPLOAD_FOLDER = 'uploads'
TEMP_FOLDER = 'temp'
MAX_FILE_SIZE = 16 * 1024 * 1024  # 16MB

# 允许的文件类型
ALLOWED_RESUME_EXTENSIONS = {'pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png'}
ALLOWED_IMAGE_EXTENSIONS = {'jpg', 'jpeg', 'png'}

# 文件保存时间（小时）
FILE_RETENTION_HOURS = 24

# ======================
# 🔥 安全配置
# ======================
# Flask密钥
SECRET_KEY = 'ai-interview-secret-key-2024'

# CORS配置
CORS_ORIGINS = ['http://localhost:3000', 'http://127.0.0.1:3000']
CORS_ALLOW_CREDENTIALS = True

# 会话配置
PERMANENT_SESSION_LIFETIME = timedelta(hours=2)

# ======================
# 🔥 日志配置
# ======================
# 日志级别
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')

# 日志文件配置
LOG_FILE = 'logs/interview_system.log'
LOG_MAX_BYTES = 10 * 1024 * 1024  # 10MB
LOG_BACKUP_COUNT = 5

# ======================
# 🔥 服务器配置
# ======================
# Flask开发服务器配置
FLASK_HOST = '0.0.0.0'
FLASK_PORT = 5000
FLASK_DEBUG = os.getenv('FLASK_DEBUG', 'True').lower() == 'true'

# WebSocket配置
SOCKETIO_ASYNC_MODE = 'threading'
SOCKETIO_CORS_ALLOWED_ORIGINS = "*"

# ======================
# 🔥 前端配置
# ======================
# React开发服务器配置
REACT_HOST = 'localhost'
REACT_PORT = 3000

# API基础URL
API_BASE_URL = f'http://{FLASK_HOST}:{FLASK_PORT}'

# ======================
# 🔥 AI模型配置
# ======================
# TTS配置
TTS_VOICE = 'x4_yezi'  # 讯飞语音合成音色
TTS_SPEED = 50  # 语速 (0-100)
TTS_VOLUME = 50  # 音量 (0-100)

# ======================
# 🔥 开发/测试配置
# ======================
# 测试模式配置
TESTING = False
MOCK_AI_RESPONSES = False  # 是否模拟AI响应
MOCK_TTS = False  # 是否模拟语音合成
MOCK_ASR = False  # 是否模拟语音识别
MOCK_EMOTION = False  # 是否模拟情绪分析

# 调试配置
DEBUG_API_CALLS = True  # 是否记录API调用详情
DEBUG_WEBSOCKET = True  # 是否记录WebSocket消息

# ======================
# 🔥 性能配置
# ======================
# 并发配置
MAX_CONCURRENT_SESSIONS = 10  # 最大并发面试会话数
SESSION_CLEANUP_INTERVAL = 3600  # 会话清理间隔（秒）

# 缓存配置
ENABLE_CACHE = True
CACHE_TIMEOUT = 300  # 缓存超时时间（秒）


# ======================
# 🔥 配置验证
# ======================
def validate_config():
    """验证配置的有效性"""
    errors = []

    # 检查必需的API密钥
    if not SPARK_APPID or SPARK_APPID == 'your_spark_appid':
        errors.append("❌ 请配置有效的SPARK_APPID")

    if not SPARK_APIKey or SPARK_APIKey == 'your_spark_api_key':
        errors.append("❌ 请配置有效的SPARK_APIKey")

    if not SPARK_APISecret or SPARK_APISecret == 'your_spark_api_secret':
        errors.append("❌ 请配置有效的SPARK_APISecret")

    # 检查目录
    required_dirs = [UPLOAD_FOLDER, TEMP_FOLDER, 'logs']
    for dir_path in required_dirs:
        if not os.path.exists(dir_path):
            try:
                os.makedirs(dir_path, exist_ok=True)
                print(f"✅ 创建目录: {dir_path}")
            except Exception as e:
                errors.append(f"❌ 无法创建目录 {dir_path}: {str(e)}")

    return errors


# ======================
# 🔥 配置导出
# ======================
# 导出常用配置供其他模块使用
__all__ = [
    'SPARK_APPID', 'SPARK_APIKey', 'SPARK_APISecret', 'SPARK_URL', 'SPARK_DOMAIN',
    'RTASR_APPID', 'RTASR_APIKey',
    'OCR_URL', 'FACE_COMPARE_URL',
    'RESUME_IMG', 'REGISTERED_IMG', 'CAPTURED_IMG',
    'OUTPUT_PCM_PATH', 'OUTPUT_WAV_PATH',
    'DEFAULT_INTERVIEW_ROUNDS', 'QUESTION_TIME_LIMIT', 'SPEAKING_TIME',
    'FACE_SIMILARITY_THRESHOLD', 'IDENTITY_VERIFICATION_REQUIRED',
    'EMOTION_SAMPLE_RATE', 'ENABLE_EMOTION_ANALYSIS',
    'UPLOAD_FOLDER', 'TEMP_FOLDER', 'MAX_FILE_SIZE',
    'SECRET_KEY', 'FLASK_HOST', 'FLASK_PORT', 'FLASK_DEBUG',
    'validate_config'
]

# ======================
# 🔥 配置初始化
# ======================
if __name__ == "__main__":
    print("🔧 AI面试系统配置检查")
    print("=" * 50)

    # 验证配置
    errors = validate_config()

    if errors:
        print("配置错误:")
        for error in errors:
            print(f"  {error}")
        print("\n请修复上述配置问题后重新启动系统。")
    else:
        print("✅ 配置检查通过")
        print(f"✅ 讯飞API配置: APPID={SPARK_APPID}")
        print(f"✅ 语音识别配置: APPID={RTASR_APPID}")
        print(f"✅ 服务器配置: {FLASK_HOST}:{FLASK_PORT}")
        print(f"✅ 面试轮次: {DEFAULT_INTERVIEW_ROUNDS}")
        print(f"✅ 每题时间: {QUESTION_TIME_LIMIT}秒")
        print(f"✅ 文件上传: {UPLOAD_FOLDER}/")
        print(f"✅ 调试模式: {FLASK_DEBUG}")

    print("=" * 50)